#!/usr/bin/env bash
# 部署脚本 - 用于将二进制文件部署到目标机器

set -euo pipefail

# 配置变量
BINARY_PATH="./dist/textlabel-server"
TARGET_USER="${1:-}"
TARGET_HOST="${2:-}"
TARGET_PATH="${3:-/opt/textlabel}"
SERVICE_NAME="textlabel"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

usage() {
    echo "使用方法: $0 <用户名> <主机地址> [目标路径]"
    echo ""
    echo "示例:"
    echo "  $0 ubuntu 192.168.1.100"
    echo "  $0 root server.example.com /usr/local/bin"
    echo ""
    echo "环境变量:"
    echo "  DEPLOY_KEY=path/to/ssh/key  # SSH 密钥路径"
    echo "  DEPLOY_PORT=22              # SSH 端口"
    exit 1
}

check_requirements() {
    log_info "检查部署要求..."
    
    if [[ -z "$TARGET_USER" || -z "$TARGET_HOST" ]]; then
        log_error "缺少必要参数"
        usage
    fi
    
    if [[ ! -f "$BINARY_PATH" ]]; then
        log_error "二进制文件不存在: $BINARY_PATH"
        log_info "请先运行: ./build_pyinstaller.sh"
        exit 1
    fi
    
    if ! command -v ssh >/dev/null 2>&1; then
        log_error "未找到 ssh 命令"
        exit 1
    fi
    
    if ! command -v scp >/dev/null 2>&1; then
        log_error "未找到 scp 命令"
        exit 1
    fi
}

setup_ssh_options() {
    SSH_OPTS="-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
    
    if [[ -n "${DEPLOY_KEY:-}" ]]; then
        SSH_OPTS="$SSH_OPTS -i $DEPLOY_KEY"
    fi
    
    if [[ -n "${DEPLOY_PORT:-}" ]]; then
        SSH_OPTS="$SSH_OPTS -p $DEPLOY_PORT"
    fi
}

test_connection() {
    log_info "测试连接到 $TARGET_USER@$TARGET_HOST..."
    
    if ! ssh $SSH_OPTS "$TARGET_USER@$TARGET_HOST" "echo 'Connection successful'" >/dev/null 2>&1; then
        log_error "无法连接到目标主机"
        log_info "请检查:"
        log_info "  1. 主机地址是否正确"
        log_info "  2. SSH 密钥是否配置"
        log_info "  3. 网络连接是否正常"
        exit 1
    fi
    
    log_info "连接测试成功"
}

deploy_binary() {
    log_info "部署二进制文件到 $TARGET_HOST:$TARGET_PATH..."
    
    # 创建目标目录
    ssh $SSH_OPTS "$TARGET_USER@$TARGET_HOST" "sudo mkdir -p $TARGET_PATH"
    
    # 复制二进制文件
    scp $SSH_OPTS "$BINARY_PATH" "$TARGET_USER@$TARGET_HOST:/tmp/textlabel-server"
    
    # 移动到目标位置并设置权限
    ssh $SSH_OPTS "$TARGET_USER@$TARGET_HOST" "
        sudo mv /tmp/textlabel-server $TARGET_PATH/textlabel-server
        sudo chmod +x $TARGET_PATH/textlabel-server
        sudo chown root:root $TARGET_PATH/textlabel-server
    "
    
    log_info "二进制文件部署完成"
}

create_systemd_service() {
    log_info "创建 systemd 服务..."
    
    ssh $SSH_OPTS "$TARGET_USER@$TARGET_HOST" "
        sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
[Unit]
Description=Text Label Server
After=network.target

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=$TARGET_PATH
ExecStart=$TARGET_PATH/textlabel-server
Restart=always
RestartSec=3
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
EOF
    "
    
    log_info "systemd 服务文件已创建"
}

setup_service() {
    log_info "配置和启动服务..."
    
    ssh $SSH_OPTS "$TARGET_USER@$TARGET_HOST" "
        sudo systemctl daemon-reload
        sudo systemctl enable $SERVICE_NAME
        sudo systemctl stop $SERVICE_NAME 2>/dev/null || true
        sudo systemctl start $SERVICE_NAME
    "
    
    # 等待服务启动
    sleep 3
    
    # 检查服务状态
    if ssh $SSH_OPTS "$TARGET_USER@$TARGET_HOST" "sudo systemctl is-active $SERVICE_NAME" | grep -q "active"; then
        log_info "服务启动成功"
    else
        log_warn "服务可能启动失败，请检查日志:"
        log_info "sudo journalctl -u $SERVICE_NAME -f"
    fi
}

show_status() {
    log_info "服务状态:"
    ssh $SSH_OPTS "$TARGET_USER@$TARGET_HOST" "sudo systemctl status $SERVICE_NAME --no-pager -l"
    
    log_info ""
    log_info "常用命令:"
    log_info "  查看日志: sudo journalctl -u $SERVICE_NAME -f"
    log_info "  重启服务: sudo systemctl restart $SERVICE_NAME"
    log_info "  停止服务: sudo systemctl stop $SERVICE_NAME"
    log_info "  启动服务: sudo systemctl start $SERVICE_NAME"
}

main() {
    log_info "开始部署文本标注系统..."
    
    check_requirements
    setup_ssh_options
    test_connection
    deploy_binary
    create_systemd_service
    setup_service
    show_status
    
    log_info "部署完成！"
    log_info "服务运行在: http://$TARGET_HOST:8000"
}

# 执行主函数
main "$@"
